local storyboard = require( "storyboard" )
local BackgroundBG = require( 'scripts.models.BackgroundBG' )
local scene = storyboard.newScene()
local totalDelta = 0

local creditsMusicChannel

function scene:updateLevelCallback()
   return function(delta)
      totalDelta = totalDelta + delta*40
      self.background:update(delta, totalDelta)
      for i = 1,#self.texts do
         self.texts[i].y = self.texts[i].y - delta*30
      end
      if(self.texts[ #self.texts ].y < -X*0.1) then
         storyboard.gotoScene("scripts.scenes.menu", {effect = "fade",time = 100})
      end
   end
end

function scene:addTextInCredits(text, size)
   local group = self.view
   local it = #self.texts
   local label = display.newText( {text=text, x=X*0.5, y=Y+(it*Y*0.2) , font=Font.get('seagram'), fontSize=size} )
   self.texts[ it+1 ] = label
   group:insert(label)
end

function scene:createScene(event)
   self.gameController = GameController:new()
   local group=self.view
   storyboard.removeAll()
   self.timers = {}

   local background = BackgroundBG.new()
   self.background = background
   group:insert(background)

   self.texts = {}
   self:addTextInCredits("Credits", 30)
   self:addTextInCredits("Thaer Latif", 15)
   self:addTextInCredits("Mauricio Poppe", 15)
   self:addTextInCredits("Edwin Guzman", 15)
   self:addTextInCredits("Gabriel Rea Velasco", 15)
   self:addTextInCredits("Miguel Velasco", 15)
   self:addTextInCredits("Alvaro Rojas", 15)
   self:addTextInCredits("Ronald Fernando Valverde", 15)
   self:addTextInCredits("Sounds thanks to www.freesfx.co.uk and www.freesound.org", 15)
end

--Methods
function scene:enterScene(event)
   logger:gameEvent("Enter Credits Scene")

   creditsMusicChannel = audio.play( creditsMusic, { channel=10, loops=-1, fadein=5000 }  )
   self.gameController:addCallback(scene:updateLevelCallback(), 'mainLoop')
   self.gameController:beginGame()
end

function scene:exitScene(event)
   logger:gameEvent("exit Credits Scene")

   self.gameController:clearAllCallbacks()
   self.gameController:stop()
end

function scene:destroyScene(event)
   logger:gameEvent("destroy Credits Scene")

   for i=#self.timers,1,-1 do
      timer.cancel(self.timers[i])
      table.remove(self.timers,i)
   end

   audio.stop( creditsMusicChannel )
   self.gameController:clearAllCallbacks()
   self.gameController:stop()
end

scene:addEventListener("createScene",scene)
scene:addEventListener("enterScene",scene)
scene:addEventListener("exitScene",scene)
scene:addEventListener("destroyScene", scene)

return scene

